<template>
	<view @click="show = true" class="view">
		<text class="title">{{data.name}}</text>
		<u-icon name="arrow-down-fill" size="16"></u-icon>
		
		<u-select v-model="show" 
			:list="classList" 
			title="选择班级"  
			label-name="name" 
			:default-value="defaultValue"
			@confirm="confirm"/>

	</view>
</template>

<script>
	import {
		getMyClassChildren
	} from '@/api/common.js'
	export default {
		name:"ClassesView",
		props: {
			hasChildren: {
				type: Boolean,
				default: false
			},
		},
		data() {
			return {
				data: {
					id: '',
					name: '',
					index: 2,
					childrenList: [],
				},
				show: false,
				
				classList: [],
			};
		},
		computed: {
			defaultValue() {
				const index = this.data.index;
				return [parseInt(index)];
			}
		},
		created() {
			if (this.hasChildren) {
				this.getChildren();
				return;
			}
			
			this.classList = this.$store.state.user.tchInfo.classList;
			if (this.$u.test.isEmpty(this.classList)) {
				this.$u.toast('暂时没有班级信息');
				return;
			}
			this.showDefault();
		},
		methods: {
			confirm(res) {
				console.log(res);

				const index = res[0].index;
				const item = this.classList[index];
				this.setChangeEvent(item, index);
				uni.setStorage({
				    key: 'classesId',
				    data: item.id,
				});
			},
			
			getChildren() {
				getMyClassChildren().then(res => {
					console.log(res);
					this.classList = res.data;
					if (this.classList.length === 0) {
						this.$u.toast('暂时没有班级信息');
					} else {
						this.showDefault();
					}
				})
			},
			
			showDefault() {
				const classesId = uni.getStorageSync('classesId');
				console.log(classesId);
				
				const index = this.classList.findIndex(item => item.id === classesId);
				console.log(`index:${index}`);
				
				if (index !== -1) {
					const  defaultItem = this.classList[index];
					this.setChangeEvent(defaultItem, index);
					return;
				}
				this.setChangeEvent(this.classList[0], 0);
			},
			
			setChangeEvent(item, index) {
				this.data = {
					...item,
					index
				}
				this.$emit('change', this.data);
			}
		}
	}
</script>

<style lang="scss">
	
	.view{
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	.title{
		font-size: 24rpx;
		font-family: PingFang SC;
		font-weight: 400;
		color: #333333;
		line-height: 65rpx;
		
		margin-right: 10rpx;
	}
</style>
